<script setup lang="ts">
import { ElMenu } from "element-plus";
import { ref, watch } from "vue";

interface Props extends /* @vue-ignore */ Partial<CP<typeof ElMenu>> {
  data: gt.components.TreeElMenuData | gt.components.TreeElMenuData[];
  modelValue?: string;
  index?: string;
}

const
  props = withDefaults(defineProps<Props>(), {
    modelValue: "", index: "", data: () => []
  }),
  emit = defineEmits<{
    (e: "update:modelValue", v: string): void;
  }>(),
  activeIndex = ref("");
watch(activeIndex, n => { emit("update:modelValue", n); });
watch(() => props.modelValue, n => { activeIndex.value = n; }, { immediate: true });
function click() {
  if (!Array.isArray(props.data) && props.data.click instanceof Function) {
    props.data.click.bind(props.data)(props.data);
  }
};
function select(i: string) {
  emit("update:modelValue", i);
}
</script>
<template>
  <el-menu v-if="Array.isArray(data)" v-model:default-active="activeIndex" v-bind="$attrs" @select="select"
    class="TreeElMenu">
    <TreeElMenu v-for="(item, i) in data" :key="i" :data="item" v-model="activeIndex" :index="index + '-' + i" />
  </el-menu>
  <el-sub-menu v-else-if="data.children && data.children.length" :index="index" v-bind="{ ...data.opt }"
    :class="(data.opt?.index || index) == modelValue ? 'is-active' : ''" @click.stop="click">
    <template #title>{{ data.name }}</template>
    <TreeElMenu v-for="(item, i) in data.children" :key="i" :data="item" v-model="activeIndex"
      :index="index + '-' + i" />
  </el-sub-menu>
  <el-menu-item v-else :index="index" v-bind="{ ...data.opt }" @click="click">{{ data.name }}</el-menu-item>
</template>